// 控制台加载确认 - 增强版
console.log('%c Portfolio website loaded successfully!', 'color: #7e57c2; font-weight: bold; font-size: 16px;');
console.log('%c 欢迎访问我的个人作品集网站！', 'color: #42a5f5;');

// 多语言支持功能
let currentLang = 'zh-CN'; // 默认语言
let translations = {};

// 加载语言文件
async function loadLanguage(lang) {
    try {
        const response = await fetch('languages.json');
        translations = await response.json();
        applyLanguage(lang);
    } catch (error) {
        console.error('加载语言文件失败:', error);
    }
}

// 应用指定语言
function applyLanguage(lang) {
    currentLang = lang;
    document.documentElement.setAttribute('data-current-lang', lang);
    
    // 更新带有data-i18n属性的元素
    document.querySelectorAll('[data-i18n]').forEach(el => {
        const key = el.getAttribute('data-i18n');
        if (translations[lang] && translations[lang][key]) {
            el.textContent = translations[lang][key];
        }
    });
    
    // 更新带有data-i18n-placeholder属性的元素
    document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
        const key = el.getAttribute('data-i18n-placeholder');
        if (translations[lang] && translations[lang][key]) {
            el.setAttribute('placeholder', translations[lang][key]);
        }
    });
    
    // 更新语言按钮状态
    document.querySelectorAll('.lang-btn').forEach(btn => {
        btn.classList.remove('active');
        if (btn.id === 'lang-' + (lang === 'zh-CN' ? 'zh' : 'en')) {
            btn.classList.add('active');
        }
    });
}

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 加载默认语言
    loadLanguage(currentLang);
    
    // 添加语言切换按钮事件监听
    document.getElementById('lang-zh').addEventListener('click', () => loadLanguage('zh-CN'));
    document.getElementById('lang-en').addEventListener('click', () => loadLanguage('en-US'));
    
    // 主题切换功能
    const themeToggle = document.getElementById('theme-toggle');
    const themeIcon = themeToggle.querySelector('i');
    
    // 检查本地存储中的主题偏好
    const savedTheme = localStorage.getItem('theme');
    
    // 如果有保存的主题，应用它；否则使用系统偏好
    if (savedTheme === 'light') {
        document.documentElement.classList.add('light');
        themeIcon.classList.remove('fa-solid', 'fa-sun');
        themeIcon.classList.add('fa-solid', 'fa-moon');
    } else if (savedTheme === 'dark') {
        document.documentElement.classList.remove('light');
        themeIcon.classList.remove('fa-solid', 'fa-moon');
        themeIcon.classList.add('fa-solid', 'fa-sun');
    } else {
        // 检测系统偏好
        if (window.matchMedia('(prefers-color-scheme: light)').matches) {
            document.documentElement.classList.add('light');
            themeIcon.classList.remove('fa-solid', 'fa-sun');
            themeIcon.classList.add('fa-solid', 'fa-moon');
            localStorage.setItem('theme', 'light');
        } else {
            document.documentElement.classList.remove('light');
            themeIcon.classList.remove('fa-solid', 'fa-moon');
            themeIcon.classList.add('fa-solid', 'fa-sun');
            localStorage.setItem('theme', 'dark');
        }
    }
    
    // 添加主题切换事件监听
    themeToggle.addEventListener('click', function() {
        const isLight = document.documentElement.classList.toggle('light');
        
        // 更新图标
        if (isLight) {
            themeIcon.classList.remove('fa-solid', 'fa-sun');
            themeIcon.classList.add('fa-solid', 'fa-moon');
            localStorage.setItem('theme', 'light');
        } else {
            themeIcon.classList.remove('fa-solid', 'fa-moon');
            themeIcon.classList.add('fa-solid', 'fa-sun');
            localStorage.setItem('theme', 'dark');
        }
    });
    
    // 创建通知元素
    function createNotification(message, type = 'success') {
        // 移除已存在的通知
        const existingNotification = document.querySelector('.notification');
        if (existingNotification) {
            existingNotification.remove();
        }
        
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.textContent = message;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            z-index: 10000;
            transform: translateX(100%);
            opacity: 0;
            transition: transform 0.5s ease, opacity 0.5s ease;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
        `;
        
        // 根据类型设置背景色 - 与深色主题匹配
        if (type === 'success') {
            notification.style.backgroundColor = '#4caf50';
        } else if (type === 'error') {
            notification.style.backgroundColor = '#ef5350';
        } else if (type === 'info') {
            notification.style.backgroundColor = '#42a5f5';
        }
        
        document.body.appendChild(notification);
        
        // 显示通知
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
            notification.style.opacity = '1';
        }, 10);
        
        // 3秒后隐藏通知
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            notification.style.opacity = '0';
            setTimeout(() => notification.remove(), 500);
        }, 3000);
        
        return notification;
    }
    
    // 表单提交处理 - 增强版
    const contactForm = document.getElementById('contactForm');
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const name = document.getElementById('name').value;
            const email = document.getElementById('email').value;
            const subject = document.getElementById('subject').value;
            const message = document.getElementById('message').value;
            
            // 表单验证增强
            let isValid = true;
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            
            if (!name.trim()) {
                isValid = false;
                document.getElementById('name').classList.add('error');
            } else {
                document.getElementById('name').classList.remove('error');
            }
            
            if (!email.trim() || !emailRegex.test(email)) {
                isValid = false;
                document.getElementById('email').classList.add('error');
            } else {
                document.getElementById('email').classList.remove('error');
            }
            
            if (!subject.trim()) {
                isValid = false;
                document.getElementById('subject').classList.add('error');
            } else {
                document.getElementById('subject').classList.remove('error');
            }
            
            if (!message.trim()) {
                isValid = false;
                document.getElementById('message').classList.add('error');
            } else {
                document.getElementById('message').classList.remove('error');
            }
            
            if (!isValid) {
                createNotification(translations[currentLang] && translations[currentLang]['validation.requiredAll'] || '请检查并填写所有必填字段', 'error');
                return;
            }
            
            // 模拟表单提交 - 带加载状态
            const submitButton = contactForm.querySelector('button[type="submit"]');
            const originalButtonText = submitButton.innerHTML;
            submitButton.disabled = true;
            submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ' + (translations[currentLang] && translations[currentLang]['form.sending'] || '发送中...');
                submitButton.style.minWidth = '140px';
            
            // 模拟网络请求延迟
            setTimeout(() => {
                console.log('表单提交数据:', {
                    name,
                    email,
                    subject,
                    message
                });
                
                // 显示提交成功消息
                createNotification(translations[currentLang] && translations[currentLang]['notification.success'] || '您的消息已发送成功！我会尽快回复您。');
                
                // 重置表单
                contactForm.reset();
                
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = originalButtonText;
            }, 1500);
        });
        
        // 添加表单输入时的验证
        const formInputs = contactForm.querySelectorAll('input, textarea');
        formInputs.forEach(input => {
            input.addEventListener('input', function() {
                this.classList.remove('error');
            });
        });
    }
    
    // 平滑滚动导航 - 增强版
    const navLinks = document.querySelectorAll('a[href^="#"]');
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            
            if (targetElement) {
                // 关闭移动菜单（如果打开）
                const navLinksContainer = document.querySelector('.nav-links');
                if (navLinksContainer && navLinksContainer.classList.contains('active')) {
                    navLinksContainer.classList.remove('active');
                }
                
                // 平滑滚动到目标位置
                window.scrollTo({
                    top: targetElement.offsetTop - 80, // 考虑导航栏高度
                    behavior: 'smooth'
                });
                
                // 添加滚动指示器动画
                // 滚动指示器已通过CSS实现，移除JavaScript版本
            }
        });
    });
    
    // 导航栏滚动效果 - 增强版
    const navbar = document.getElementById('navbar');
    if (navbar) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 100) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }
        });
    }
    
    // 移动菜单切换 - 增强版
    const menuToggle = document.querySelector('.menu-toggle');
    const navLinksContainer = document.querySelector('.nav-links');
    
    if (menuToggle && navLinksContainer) {
        menuToggle.addEventListener('click', function() {
            navLinksContainer.classList.toggle('active');
            
            // 切换菜单图标
            const icon = menuToggle.querySelector('i');
            if (icon) {
                if (navLinksContainer.classList.contains('active')) {
                    icon.classList.remove('fa-bars');
                    icon.classList.add('fa-times');
                } else {
                    icon.classList.remove('fa-times');
                    icon.classList.add('fa-bars');
                }
            }
            
            // 添加菜单打开/关闭动画
            if (navLinksContainer.classList.contains('active')) {
                document.body.style.overflow = 'hidden'; // 防止背景滚动
            } else {
                document.body.style.overflow = ''; // 恢复背景滚动
            }
        });
    }
    
    // 项目卡片、技能标签和按钮交互效果已通过CSS实现，移除JavaScript版本
    
    // 图片懒加载的过渡效果
    const lazyImages = document.querySelectorAll('img[loading="lazy"]');
    lazyImages.forEach(img => {
        // 初始状态
        img.style.opacity = '0';
        img.style.transform = 'scale(0.95)';
        img.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
        
        // 图片加载完成后显示
        img.addEventListener('load', function() {
            this.style.opacity = '1';
            this.style.transform = 'scale(1)';
        });
        
        // 如果图片已经加载完成
        if (img.complete) {
            img.style.opacity = '1';
            img.style.transform = 'scale(1)';
        }
    });
    
    // 添加滚动监听，为元素添加动画效果 - 增强版
    const animateOnScroll = function() {
        const fadeElements = document.querySelectorAll('.fade-in');
        const slideUpElements = document.querySelectorAll('.slide-in-up');
        const slideLeftElements = document.querySelectorAll('.slide-in-left');
        const slideRightElements = document.querySelectorAll('.slide-in-right');
        
        // 处理淡入元素
        fadeElements.forEach(element => {
            const elementPosition = element.getBoundingClientRect().top;
            const screenPosition = window.innerHeight / 1.3;
            
            if (elementPosition < screenPosition && !element.classList.contains('animated')) {
                element.classList.add('animated');
            }
        });
        
        // 处理上滑元素
        slideUpElements.forEach(element => {
            const elementPosition = element.getBoundingClientRect().top;
            const screenPosition = window.innerHeight / 1.3;
            
            if (elementPosition < screenPosition && !element.classList.contains('animated')) {
                element.classList.add('animated');
            }
        });
        
        // 处理左滑元素
        slideLeftElements.forEach(element => {
            const elementPosition = element.getBoundingClientRect().top;
            const screenPosition = window.innerHeight / 1.3;
            
            if (elementPosition < screenPosition && !element.classList.contains('animated')) {
                element.classList.add('animated');
            }
        });
        
        // 处理右滑元素
        slideRightElements.forEach(element => {
            const elementPosition = element.getBoundingClientRect().top;
            const screenPosition = window.innerHeight / 1.3;
            
            if (elementPosition < screenPosition && !element.classList.contains('animated')) {
                element.classList.add('animated');
            }
        });
        
        // 导航栏高亮当前活动部分
        const sections = document.querySelectorAll('section[id]');
        const navLinks = document.querySelectorAll('.nav-links a');
        
        let current = '';
        sections.forEach(section => {
            const sectionTop = section.offsetTop;
            const sectionHeight = section.clientHeight;
            if (window.scrollY >= sectionTop - 100) {
                current = section.getAttribute('id');
            }
        });
        
        navLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href') === `#${current}`) {
                link.classList.add('active');
            }
        });
    };
    
    // 首次检查
    animateOnScroll();
    
    // 滚动时检查
    window.addEventListener('scroll', function() {
        // 使用防抖技术减少滚动事件触发频率
        if (!window.scrollTimeout) {
            window.scrollTimeout = setTimeout(() => {
                animateOnScroll();
                window.scrollTimeout = null;
            }, 50);
        }
    });
    
    // 修复Font Awesome图标显示问题的回退方案
    const checkFontAwesome = function() {
        const fontAwesomeTest = document.createElement('i');
        fontAwesomeTest.className = 'fas fa-check';
        fontAwesomeTest.style.position = 'absolute';
        fontAwesomeTest.style.visibility = 'hidden';
        document.body.appendChild(fontAwesomeTest);
        
        // 检查图标是否加载成功
        const isFontAwesomeLoaded = window.getComputedStyle(fontAwesomeTest).getPropertyValue('font-family').includes('FontAwesome');
        
        if (!isFontAwesomeLoaded) {
            console.warn('Font Awesome 可能未加载成功，使用回退图标。');
            // 替换所有Font Awesome图标为简单文本图标
            const icons = document.querySelectorAll('.fas, .fab');
            icons.forEach(icon => {
                const iconClass = icon.className;
                if (iconClass.includes('fa-envelope')) icon.textContent = '✉';
                else if (iconClass.includes('fa-phone')) icon.textContent = '📞';
                else if (iconClass.includes('fa-map-marker-alt')) icon.textContent = '📍';
                else if (iconClass.includes('fa-github')) icon.textContent = '💻';
                else if (iconClass.includes('fa-linkedin')) icon.textContent = '🔗';
                else if (iconClass.includes('fa-twitter')) icon.textContent = '🐦';
                else if (iconClass.includes('fa-instagram')) icon.textContent = '📸';
                else if (iconClass.includes('fa-bars')) icon.textContent = '☰';
                else if (iconClass.includes('fa-times')) icon.textContent = '✕';
                else if (iconClass.includes('fa-spinner')) icon.textContent = '⏳';
                icon.className = 'fallback-icon';
                icon.style.fontSize = 'inherit';
            });
        }
        
        document.body.removeChild(fontAwesomeTest);
    };
    
    // 页面加载后检查Font Awesome
    setTimeout(checkFontAwesome, 1000);
    
    // 添加页面加载动画 - 与深色主题匹配
    const pageLoader = document.createElement('div');
    pageLoader.className = 'page-loader';
    pageLoader.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: #121212;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 99999;
        transition: opacity 0.5s ease, visibility 0.5s ease;
    `;
    
    const loaderContent = document.createElement('div');
    loaderContent.style.cssText = `
        text-align: center;
    `;
    
    const loaderIcon = document.createElement('div');
    loaderIcon.style.cssText = `
        width: 50px;
        height: 50px;
        border: 3px solid #2a2a2a;
        border-top: 3px solid #7e57c2;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 20px;
    `;
    
    const loaderText = document.createElement('p');
    loaderText.textContent = '加载中...';
    loaderText.style.cssText = `
        color: #7e57c2;
        font-size: 18px;
        font-weight: 500;
    `;
    
    // 添加旋转动画
    const style = document.createElement('style');
    style.textContent = `
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    `;
    document.head.appendChild(style);
    
    loaderContent.appendChild(loaderIcon);
    loaderContent.appendChild(loaderText);
    pageLoader.appendChild(loaderContent);
    document.body.appendChild(pageLoader);
    
    // 页面加载完成后隐藏加载动画
    window.addEventListener('load', function() {
        setTimeout(() => {
            pageLoader.style.opacity = '0';
            pageLoader.style.visibility = 'hidden';
        }, 500);
    });
    
    // 显示欢迎消息
    setTimeout(() => {
        createNotification('欢迎访问我的个人作品集网站！', 'info');
    }, 1500);
});